package com.fingard.dsp.bank.directbank.chanpay01.chanpay01Util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Util {
	
	public static final String PROP_NAME_RET_CODE = "RET_CODE";
	/** 属性常量：返回描述 */
	public static final String PROP_NAME_ERR_MSG = "ERR_MSG";
	 /**
     * @Comments ：解压缩文件
     * @param zipFromPathName 压缩文件所处路径
     * @param zipTargetPathName 解压缩后所处路径
     * @throws Exception 
     */
	public static void upzipFile(String zipFromPathName, String zipTargetPathName) throws Exception {
		/*if (!zipTargetPathName.endsWith(File.separator)) {
			zipTargetPathName += File.separator;
		}*/
        ZipFile zipFile = null;
        FileOutputStream os = null;
        InputStream is = null;
		try {
            //根据zip文件创建zipFile 对象 此类的作用是从zip文件中读取条目
            zipFile = new ZipFile(zipFromPathName);
            ZipEntry zn = null;
            String entryName = null;
            String targetFileName = null;
            byte[] buffer = new byte[4096];
            int bytes_read;
            //获取zip文件里所有的文件条目的名字
            Enumeration entrys = zipFile.entries();
            //循环遍历所有的文件条目的名字
            while (entrys.hasMoreElements()) {
                zn = (ZipEntry) entrys.nextElement();
                //获得每一条文件的名字
                entryName = zn.getName();
                targetFileName = zipTargetPathName + entryName;
                if (zn.isDirectory()) {
                    new File(targetFileName).mkdirs();
                } else {
                    new File(targetFileName).getParentFile().mkdirs();
                }
                File targetFile = new File(targetFileName);
                //打开文件输出流
                os = new FileOutputStream(targetFile);
                //从zipfile对象中打开entry的输入流、
                is = zipFile.getInputStream(zn);
                while ((bytes_read = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytes_read);
                }
            }
            System.out.println("解压缩" + zipFromPathName + "成功!");
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
		    if (zipFile != null) {
		        zipFile.close();
            }
		    if (os != null) {
		        os.close();
            }
		    if (is != null) {
		        is.close();
            }
        }
	}
	public static String formatXml_UTF8(Document doc) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding(S.ENCODING_utf8);
			format.setIndent(false);
			format.setNewlines(false);
			format.setNewLineAfterDeclaration(false);
			/*
			format.setLineSeparator("\n");
			 */
			StringWriter out = new StringWriter();
			XMLWriter writer = new XMLWriter(out, format);
			writer.write(doc);
			writer.close();
			return out.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static String findHeaderAttr(Header head) throws Exception {
		if (head == null)
			return "";
		String val = head.getValue();
		if (StringUtils.isBlank(val)) {
			return "";
		}
		String msg = URLDecoder.decode(val, S.ENCODING_utf8);
		System.out.println("收到HTTP-HEAD属性[" + head.getName() + "]=" + msg);
		return msg;
	}
	/**
	 * 安照GBK编码截取计算字符串实际的字节长度，主要用于存储如数据库时，限定字符长度使用。<br>
	 * varchar2(2000)的字段，只能存储1000个中文字符
	 * @param src 原始字符串
	 * @param len 指定的长度
	 * @return 
	 */
	public static String substringByByte(String src, final int len) {
		if (src.length() < (len / 2))
			return src;

		try {
			byte[] bs = src.getBytes(S.ENCODING_gbk);

			//字符长度小于给定长度
			if (bs.length <= len) {
				return src;
			}

			//如果没有双字节字
			if (bs.length == src.length()) {
				return src.substring(0, len);
			}

			//处理双字节情况
			StringBuilder sb = new StringBuilder();
			int size = 0;
			int cnt = 0;
			for (Character ch : src.toCharArray()) {
				cnt = Character.toString(ch).getBytes(S.ENCODING_gbk).length;
				size += cnt;
				if (size <= len) {
					sb.append(ch);
				}
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static String getCurrentTimestamp() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Calendar calendar = Calendar.getInstance();
		String createTime = format.format(calendar.getTime());
		return createTime;
	}
}
